package cn.com.artemis.security.exceptions;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Token无效
 * @Author enbool
 * @create 2019/11/12 10:42
 */
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    public AuthExceptionEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    private ObjectMapper objectMapper;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Map<String, Object> ret = new HashMap<>();
        ret.put("code", 401);

        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        try {
            if(cause instanceof InvalidTokenException) {
                ret.put("message", "Token无效");
            }else {

                ret.put("message", authException.getMessage());
            }
            response.getWriter().write(objectMapper.writeValueAsString(ret));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
